/* eslint-disable */
let { list } = require('./src/mock')
const bodyParser = require('body-parser')
const JWT = require('jsonwebtoken')
const key = '6666666666'
const userList = [{
	user: 'admin',
	pwd: 'admin',
	roles: ['user', 'admin']
}, {
	user: '学生',
	pwd: '12345',
	roles: ['user']
}, {
	user: '1908a',
	pwd: '35',
	roles: ['user']
}]
module.exports = {
	devServer: {
		before(app) {
			app.use(bodyParser.json())

			// 列表分页请求接口 
			app.get('/api/list', (req, res) => {
				// 获取每页个数和当前页码
				const { pageCode = 1, pageSize = 10, searchValue = ''/*搜索的数据*/ } = req.query
				// 模糊搜索
				const newList = list.filter(v => v.name.includes(searchValue) || v.desc.includes(searchValue))
				res.send({
					code: 200,
					mess: 'success',
					data: {
						// 分页器公式
						data: newList.slice((pageCode - 1) * pageSize, pageCode * pageSize),
						total: newList.length
					},
				})
			})

			// 列表删除 单个|多个 接口
			app.post('/api/delete', (req, res) => {
				const { id } = req.body
				// 筛选所有和要删除的id不一样的值
				list = list.filter(v => !id.includes(v.id))
				res.send({
					code: 200,
					mess: 'success',
					data: null
				})
			})

			// 登录接口
			app.post('/api/login', (req, res) => {
				const { user, pwd } = req.body
				const currUser = userList.find(v => v.user === user && v.pwd === pwd)
				if (currUser) {
					res.send({
						code: 200,
						token: JWT.sign(currUser, key),
						mess: '登录成功'
					})
				} else {
					res.send({
						code: 403,
						data: null,
						mess: '账户密码错误, 请重新登录'
					})
				}
			})

			// 返回用户权限接口
			app.post('/api/user/permission', (req, res) => {
				const { token } = req.body;
				const { roles } = JWT.verify(token, key)
				res.send({
					code: 200,
					roles
				})
			})


			// 添加数据接口
			app.post('/api/list/add', (req, res) => {
				req.body.id = new Date().getTime().toString()
				list.unshift(req.body);
				res.send({
					code: 200,
					mess: '添加成功！'
				})
			})
		}
	}
}